<?php

namespace app\admin\controller;
use think\facade\Session;
use app\admin\model\Role;
use app\admin\model\Admin;
use app\admin\controller\Base;
use think\Request;
use think\Db;
class Roles extends Base
{
    //角色权限列表渲染输出
    public function roleList()
    {
		$rolepid = $this->foreachroleid(Session::get('Adminuser.roles'));
		if($rolepid){
			$role = Db::name('role')->where('id','in',$rolepid.','.Session::get('Adminuser.roles'))->order('pid','asc')->paginate(25)->each(function($item, $key){
				$adminname = Db::name('admin')->where('roles',$item['id'])->field('name')->select()->toArray();
				$item['username'] = $adminname;
				$status = ['0'=>'已停用','1'=>'已启用'];
				$item['status'] = $status[$item['status']];
				if($item['id'] == Session::get('Adminuser.roles') || $item['pid'] == 0){
					$item['center'] = 0;
				}else{
					$item['center'] = 1;
				}
				return $item;
			});
		}else{
			$role = Db::name('role')->where('id',Session::get('Adminuser.roles'))->order('pid','asc')->paginate(25)->each(function($item, $key){
				$adminname = Db::name('admin')->where('roles',$item['id'])->field('name')->select()->toArray();
				$item['username'] = $adminname;
				$status = ['0'=>'已停用','1'=>'已启用'];
				$item['status'] = $status[$item['status']];
				if($item['id'] == Session::get('Adminuser.roles') || $item['pid'] == 0){
					$item['center'] = 0;
				}else{
					$item['center'] = 1;
				}
				return $item;
			});
		}
		return view('list',['roles'=>$role]);
    }
	
	public function foreachroleid($roleid)
	{
		$roleids = "";
		if(!empty($roleid) || is_numeric($roleid)){
			$rolepid = Db::name('role')->where('pid',$roleid)->field('id')->select();
			if(!$rolepid->isEmpty()){
				foreach($rolepid as $r){
					$roleids .= $r['id'] . ',';
					$roleids .= $this->foreachroleid($r['id']).',';
				}
			}
		}
		if(!empty($roleids)){
			return trim($roleids,',');
		}else{
			return false;
		}
	}
	
    //请求数据源  添加/编辑在使用
    public function getData(Request $request)
    {
        if(request()->isAjax()){
        //查询一级ID
        $one = Db::name('rule')->field(['id','pid','title'])->select()->toArray();
		$info = alldigui($one,0,0);
        return json($info);
        }
    }
    
    //角色添加
    public function add(Request $request)
    {
        //判断是否为ajax请求
        if(request()->isAjax()){
            $sorts = Role::all();
    		$sort = 1;
    		//自动排序
    		foreach($sorts as $key=>$val){
    			if(!empty($val['orders'])){
    				$sort = $val["orders"]+1;
    			}
    		}
    		 //接收提交过来的信息
    		$data = $request->param();
    		$info['name'] = $data['name'];
    		$info['info'] = $data ['info'];
			if(isset($data['select']) && is_numeric($data['select'])){
				$info['pid'] = $data['select'];
				unset($data['select']);
			}
    		//删除数组中指定元素
    		unset($data['name']);
    		unset($data['info']);
			if(isset($data['jurisdiction'])){
				if($data['jurisdiction'] == '/-all-/'){
					$info['jurisdiction'] = $data['jurisdiction'];
				}else{
					$info['jurisdiction'] = '/-all-/';
				}
				unset($data['jurisdiction']);
			}else{
				if(!empty($data)){
					foreach($data as $k=>$r){
						if(!is_numeric($r)){
							unset($data[$k]);
						}
					}
					//将键转换为数字键
					$array = array_values($data);
					//数组转字符串
					$info['jurisdiction'] = implode(',',$array);
				}else{
					$info['jurisdiction'] = NULL;
				}
			}
    		//创建时间
    		$info['create_time'] = time();
    		//修改时间
    		$info['update_time'] = time();
    		//排序
    		$info['orders'] = $sort;
    		//判断角色名是否为空
    		if(empty($info['name'])){
    			$this -> error("角色名不能为空!");
    			return false;
    		}else{
    		    //判断角色名是否存在
    			if(Role::get(['name'=>$info['name']])){
    			$this -> error("角色名已存在!");
    			return false;	
    		}else{
    			$res = Role::insert($info);
    			//提示信息
    			if($res){
    			    $this -> logs("管理员：".Session::get('Adminuser.name')."添加角色 [ID: ".$info['name'].'] 成功!');
    				$this -> success("添加成功!",'Roles/rolelist');
    			}else{
					$this -> logs("管理员：".Session::get('Adminuser.name')."添加角色 [ID: ".$info['name'].'] 失败!');
    				$this -> error("添加失败!");
    			    }
    		    }
    	    }
        }
		$roleid = "";
		$allrolesid = Db::name('rule')->field('id,level')->select();
		foreach($allrolesid as $key=>$val){
			if($val['level'] != 2){
				unset($allrolesid[$key]);
			}else{
				$roleid .= $val['id'] . ',';
			}
		}
		if(!empty($roleid)){
			$roleid = substr($roleid,0,-1);
		}
		$roles = Db::name('role')->field('id,name,pid')->select()->toArray();
		foreach($roles as $ke=>$v){
			$roles[$ke]['id'] = $v['id'];
			$roles[$ke]['value'] = $v['id'];
			if($v['pid'] == 0 || $v['id'] == 1){
				$roles[$ke]['selected'] = true;
			}
		}
		$roles = alldigui($roles,0,0);
        return view('add',['roleid'=>$roleid,'rolepids'=>json_encode($roles,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);
    }


    //角色管理列表编辑
    public function edit(Request $request)
    {
        //判断是否为ajax请求
        if(request()->isAjax()){
    	    //接收提交过来的信息
    		$data = $request->param();
		    //获取对应ID的角色信息
		    $roles = Role::get($data['id']);
    		$info['name'] = $data['name'];
    		$info['info'] = $data['info'];
    		$info['id'] = $data['id'];
			if(isset($data['select']) && is_numeric($data['select'])){
				if($data['select'] != $roles['pid']){
					$info['pid'] = $data['select'];
					unset($data['select']);
				}
			}
    		//删除数组中指定元素
    		unset($data['name']);
    		unset($data['info']);
    		unset($data['id']);
			if(isset($data['jurisdiction'])){
				if($data['jurisdiction'] == '/-all-/'){
					$info['jurisdiction'] = $data['jurisdiction'];
				}else{
					$info['jurisdiction'] = '/-all-/';
				}
				unset($data['jurisdiction']);
			}else{
				if(!empty($data)){
					foreach($data as $k=>$r){
						if(!is_numeric($r)){
							unset($data[$k]);
						}
					}
					//将键转换为数字键
					$array = array_values($data);
					//数组转字符串
					$info['jurisdiction'] = implode(',',$array);
				}else{
					$info['jurisdiction'] = NULL;
				}
			}
    		//修改时间
    		$info['update_time'] = time();
    		//提示信息
    		if(empty($info['name'])){
    			$this -> error("角色名不能为空!");
    			return false;
    		}else{
    		    //判断角色名是否存在
    			if(Role::get(['name'=>$info['name']] && $info['name'] != $roles['name'])){
    			$this -> error("角色名已存在!");
    			return false;	
        		}else{
        			$res = Role::update($info);
        			//提示信息
        			if($res){
        			    $this -> logs("管理员：".Session::get('Adminuser.name')."修改角色 [ID: ".$info['id'].'] 成功!');
        				$this -> success("修改成功!",'Roles/rolelist');
        			}else{
						$this -> logs("管理员：".Session::get('Adminuser.name')."修改角色 [ID: ".$info['id'].'] 失败!');
        				$this -> error("修改失败!");
        			    }
        		    }
    	        }
            }
			
        $id = $request->param('id');
		//获取对应ID的角色信息
		$roles = Db::name('role')->find($id);
		if($roles['jurisdiction'] != '/-all-/'){
			$roles['jurcheck'] = '0';
			//字符串转数组
			$array = explode(',',$roles['jurisdiction']);
			//删除0级1级的url，以防模板渲染错误
			foreach ($array as $key => $val){
			    $info = Db::name('rule')->where('id',$val)->field('level')->find();
			    if($info['level'] != 2){
			        unset($array[$key]);
			    }
			}
			//转为字符串
			$roles['jurisdiction'] = implode(',',$array);
			$roleid = $roles['jurisdiction'];
		}else{
			$roles['jurisdiction'] = "";
			$roles['jurcheck'] = '1';
			$allrolesid = Db::name('rule')->field('id,level')->select();
			foreach($allrolesid as $key=>$val){
				if($val['level'] != 2){
					unset($allrolesid[$key]);
				}else{
					$roles['jurisdiction'] .= $val['id'] . ',';
				}
			}
			$roleid = substr($roles['jurisdiction'],0,-1);
			if(!empty($roleid)){
				$roles['jurisdiction'] = $roleid;
			}
		}
		$rolespid = Db::name('role')->field('id,name,pid')->select()->toArray();
		foreach($rolespid as $ke=>$v){
			$rolespid[$ke]['id'] = $v['id'];
			$rolespid[$ke]['value'] = $v['id'];
			if($roles['pid'] == 0){
				$rolespid[$ke]['disabled'] = true;
			}else if($roles['pid'] == $v['id']){
				$rolespid[$ke]['selected'] = true;
			}else if($roles['id'] == $v['id']){
				$rolespid[$ke]['disabled'] = true;
			}
			
		}
		$rolespid = alldigui($rolespid,0,0);
		return view('edit',['roles'=>$roles,'roleid'=>$roleid,'rolepids'=>json_encode($rolespid,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);
    }
    

    //角色管理列表删除/批量删除
    public function deletes(Request $request)
    {
        //判断是否为ajax请求
        if(request()->isAjax()){
            //接收提交过来的信息
            $id = $request->param('id');
            //转为数组
            $array = explode(',',$id);
			foreach(array_unique(array_filter($array)) as $ke=>$vs){
				$p = Db::name('role')->find($vs);
				if($p['pid'] == 0){
					unset($array[$ke]);
				}else{
				$pid = $this->foreachroleid($vs);
					if(!empty($pid)){
						$parray = explode(',',$pid);
						$array = array_merge($array,$parray);
					}
				}
			}
			$array = array_unique(array_filter($array));
			if(!empty($array)){
				$admin = Db::name('admin')->where('id',Session::get('Adminuser.id'))->field('roles')->find();
				foreach($array as $key=>$val){
					if($val == $admin['roles']){
						unset($array[$key]);
					}
					$checkadmin = Db::name('admin')->where('roles',$val)->find();
					if(!empty($checkadmin)){
						unset($array[$key]);
					}
				}
				if(!empty($array)){
					//删除操作
					$res =Role::destroy($array);
					if($res){
						$this -> logs("管理员：".Session::get('Adminuser.name')."删除角色：".implode(",",$array));
						$this -> success("删除成功!",'Roles/rolelist');
					}else{
						$this -> logs("管理员：".Session::get('Adminuser.name')."删除角色：".implode(",",$array)."失败");
						$this -> error("删除失败!");
					}
				}else{
					$this->error("正在使用的角色不可删除!");
				}
			}else{
				$this->error("当前无可操作数据!");
			}
        }
		
    }
    
    //状态变更
    public function setStatus(Request $request)
    {
        if(request()->isAjax()){
            //接收ID
            $id = $request->param('id');
			$roles = Db::name('role')->find($id);
			if($roles['pid'] != 0 || $id != Session::get('Adminuser.roles')){
				$status = ['status'=>1];
				if($roles['status'] == 1){
					$status = ['status'=>0];
				}
				//执行更新
				$res = Db::name('role')->where('id',$id)->update($status);
				if($res){
					$this -> logs("管理员：".Session::get('Adminuser.name')."变更角色[".$roles['name']."]状态成功!");
				    $this->success("状态已变更!",'Roles/rolelist');
				}else{
					$this -> logs("管理员：".Session::get('Adminuser.name')."变更角色[".$roles['name']."]状态失败!");
				    $this->error("状态变更失败!");
				}
			}else{
				$this->error("当前无可操作数据!");
			}
        }
    }
    
    //角色搜索
    public function search(Request $request)
    {
		$rolesid = Session::get('Adminuser.roles');
		$keywords = $request->param('keywords');
		$roleid = $this->foreachroleid(Session::get('Adminuser.roles'));
		if($roleid){
			$rolesid .= ','.$roleid;
		}
		//进行模糊查询
		$role = Role::where('name|info','like','%'.$keywords.'%')->where('id','in',$rolesid)->order('pid','asc')->paginate(25,false,['query'=>request()->param()])->each(function($item, $key){
			$username = Admin::where('roles',$item['id'])->field('name')->select()->toArray();
			$item['username'] = $username;
			if($item['id'] == Session::get('Adminuser.roles') || $item['pid'] == 0){
				$item['center'] = 0;
			}else{
				$item['center'] = 1;
			}
			return $item;
		});
        return view('list',['roles'=>$role]);
    }
}
